package com.yidiandao.business.ui.main.shoppingcart.confirmorder;

import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.yidiandao.business.R;
import com.yidiandao.business.base.SuperBaseFragment;
import com.yidiandao.business.data.Consignee;
import com.yidiandao.business.ui.addressabout.chooseaddress.ChooseAddressActivity;
import com.yidiandao.business.ui.main.shoppingcart.cashier.CashierActivity;
import com.yidiandao.business.ui.main.shoppingcart.choosecoupon.ChooseCouponActivity;
import com.yidiandao.business.ui.main.shoppingcart.choosedelivery.ChooseShippingWayActivity;
import com.yidiandao.business.ui.main.shoppingcart.chooseinvoice.ChooseInvoiceActivity;
import com.yidiandao.business.ui.main.shoppingcart.choosepayway.ChoosePayWayActivity;
import com.yidiandao.business.ui.main.shoppingcart.chooseredpacket.ChooseRedPacketActivity;
import com.yidiandao.business.ui.main.shoppingcart.inventory.InventoryActivity;
import com.yidiandao.business.ui.main.shoppingcart.multipayways.MultiPayWaysActivity;
import com.yidiandao.business.ui.main.shoppingcart.orderresult.OrderResultActivity;
import com.yidiandao.business.ui.widget.dialog.CallPhoneDialog;
import com.yidiandao.business.ui.widget.dialog.LoadingDialog;
import com.yidiandao.business.ui.widget.view.CompatScrollView;
import com.yidiandao.business.ui.widget.view.RatioLayout;
import com.yidiandao.business.utils.ImageLoader;
import com.yidiandao.business.utils.KeyboardStateHelper;
import com.yidiandao.business.utils.KeyboardUtils;
import com.yidiandao.business.utils.NumberFormatUtils;
import com.yidiandao.business.utils.TextRenderUtils;
import com.yidiandao.business.utils.UIUtils;
import com.yidiandao.business.utils.UmengUtils;

import java.util.List;

import me.grantland.widget.AutofitLayout;

/**
 * 新的确认订单页面View
 */
public class ConfirmOrderFragment extends SuperBaseFragment implements ConfirmOrderContract.View, View.OnClickListener {

    private ConfirmOrderContract.Presenter mPresenter;

    private Toolbar mToolbar;

    private LinearLayout mRootAddress;

    private TextView mTvConsignee;

    private TextView mTvPhone;

    private TextView mTvTopAddress;

    private ImageView mIvImage1;

    private ImageView mIvImage2;

    private ImageView mIvImage3;

    private TextView mTvTotalCount;

    private RelativeLayout mRootInvoice;

    private TextView mTvInvoiceInfo;

    private TextView mTvInvoiceRate;

    private RelativeLayout mRootCoupon;

    private TextView mTvCouponReduce;

    private RelativeLayout mRootRedPacket;

    private TextView mTvRedPacketUsefulCount;

    private TextView mTvRedPacketReduce;

    private TextView mTvStatisticsMoney;

    private TextView mTvDeliveryMoney;

    private TextView mTvSubmitOrder;

    private TextView mTvHelperAddress;

    private LinearLayout mRootBuyGoods;

    private CompatScrollView mScrollView;

    private LoadingDialog mLoadingDialog;

    private TextView mTvSubmitMoney;

    private RatioLayout mRatioLayout2;

    private RatioLayout mRatioLayout3;

    private AutofitLayout mLayout4;

    private TextView mTvInvoiceMoney;

    private RelativeLayout mRootDelivery;

    private TextView mTvDelivery;

    private TextView mTvServiceNumber;

    private RelativeLayout mRootServiceNumber;

    private RelativeLayout mRootPay;

    private TextView mTvPayWay;

    private TextView mTvPayRate;

    private TextView mTvPayWayMoney;

    private EditText mEtMessage;

    private LinearLayout mBottomLayout;

    private KeyboardStateHelper mKeyboardStateHelper;
    private TextView mTvCouponUsefulCount;

    public static ConfirmOrderFragment getInstance(Bundle bundle) {
        ConfirmOrderFragment fragment = new ConfirmOrderFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void setPresenter(ConfirmOrderContract.Presenter presenter) {
        mPresenter = presenter;
    }

    @Override
    public String getPagerTag() {
        return ConfirmOrderFragment.class.getSimpleName();
    }

    @Override
    public void showToast(String text) {
        UIUtils.showToast(text);
    }

    @Override
    protected void initViews() {
        mToolbar = (Toolbar) mRootView.findViewById(R.id.toolbar);
        mRootAddress = (LinearLayout) mRootView.findViewById(R.id.root_address);
        mTvConsignee = (TextView) mRootView.findViewById(R.id.tv_consignee);
        mTvPhone = (TextView) mRootView.findViewById(R.id.tv_phone);
        mTvTopAddress = (TextView) mRootView.findViewById(R.id.tv_top_address);
        mIvImage1 = (ImageView) mRootView.findViewById(R.id.iv_image_1);
        mIvImage2 = (ImageView) mRootView.findViewById(R.id.iv_image_2);
        mIvImage3 = (ImageView) mRootView.findViewById(R.id.iv_image_3);
        mTvTotalCount = (TextView) mRootView.findViewById(R.id.tv_total_count);

        mRootInvoice = (RelativeLayout) mRootView.findViewById(R.id.root_invoice);
        mTvInvoiceInfo = (TextView) mRootView.findViewById(R.id.tv_invoice_info);
        mTvInvoiceRate = (TextView) mRootView.findViewById(R.id.tv_invoice_percent);
        mRootCoupon = (RelativeLayout) mRootView.findViewById(R.id.root_coupon);
        mTvCouponReduce = (TextView) mRootView.findViewById(R.id.tv_coupon_reduce);
        mTvCouponUsefulCount = (TextView) mRootView.findViewById(R.id.tv_coupon_useful_count);
        mRootRedPacket = (RelativeLayout) mRootView.findViewById(R.id.root_red_packet);
        mTvRedPacketUsefulCount = (TextView) mRootView.findViewById(R.id.tv_red_packet_useful_count);
        mTvRedPacketReduce = (TextView) mRootView.findViewById(R.id.tv_red_packet_reduce);
        mTvStatisticsMoney = (TextView) mRootView.findViewById(R.id.tv_statistics_money);
        mTvDeliveryMoney = (TextView) mRootView.findViewById(R.id.tv_delivery_money);
        mTvSubmitOrder = (TextView) mRootView.findViewById(R.id.tv_submit_order);
        mTvHelperAddress = (TextView) mRootView.findViewById(R.id.tv_helper_address);
        mRootBuyGoods = (LinearLayout) mRootView.findViewById(R.id.root_buy_goods);
        mScrollView = (CompatScrollView) mRootView.findViewById(R.id.scroll_view);
        mTvSubmitMoney = (TextView) mRootView.findViewById(R.id.tv_submit_money);
        mRatioLayout2 = (RatioLayout) mRootView.findViewById(R.id.ratio_layout_2);
        mRatioLayout3 = (RatioLayout) mRootView.findViewById(R.id.ratio_layout_3);
        mLayout4 = (AutofitLayout) mRootView.findViewById(R.id.layout_4);
        mTvInvoiceMoney = (TextView) mRootView.findViewById(R.id.tv_invoice_money);
        mRootDelivery = (RelativeLayout) mRootView.findViewById(R.id.root_delivery);
        mTvDelivery = (TextView) mRootView.findViewById(R.id.tv_delivery);
        mTvServiceNumber = (TextView) mRootView.findViewById(R.id.tv_service_number);
        mRootServiceNumber = (RelativeLayout) mRootView.findViewById(R.id.root_service_number);
        mRootPay = (RelativeLayout) mRootView.findViewById(R.id.root_pay);
        mTvPayWay = (TextView) mRootView.findViewById(R.id.tv_pay_way);
        mTvPayRate = (TextView) mRootView.findViewById(R.id.tv_pay_rate);
        mTvPayWayMoney = (TextView) mRootView.findViewById(R.id.tv_pay_way_money);
        mEtMessage = (EditText) mRootView.findViewById(R.id.et_message);
        mBottomLayout = (LinearLayout) mRootView.findViewById(R.id.bottom_layout);

        initKeyboardAbout();
        initListeners();
    }

    private void initKeyboardAbout() {
        mKeyboardStateHelper = new KeyboardStateHelper(mScrollView);
        mKeyboardStateHelper.setOnKeyboardStateChangeListener(
                new KeyboardStateHelper.OnKeyboardStateChangeListener() {
                    @Override
                    public void onKeyboardStateChange(boolean keyboardShow) {
                        mBottomLayout.setVisibility(keyboardShow ? View.GONE : View.VISIBLE);
                    }
                });
        mEtMessage.setHorizontallyScrolling(false);
        mEtMessage.setLines(Integer.MAX_VALUE);
    }

    @Override
    protected void startLoadData() {
        mPresenter.start();
    }

    private void initListeners() {
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPresenter.setNeedRefreshShoppingCart(false);
                finishActivity();
            }
        });

        mLayout4.setOnClickListener(this);
        mRootInvoice.setOnClickListener(this);
        mRootAddress.setOnClickListener(this);
        mRootRedPacket.setOnClickListener(this);
        mRootCoupon.setOnClickListener(this);
        mRootDelivery.setOnClickListener(this);
        mRootPay.setOnClickListener(this);
        mTvSubmitOrder.setOnClickListener(this);

        mScrollView.setOnScrollListener(new CompatScrollView.OnScrollChangedListener() {
            @Override
            public void onScrollChanged(int x, int y, int oldxX, int oldY) {
                if (y > mRootBuyGoods.getTop()) {
                    mTvHelperAddress.setVisibility(View.VISIBLE);
                } else {
                    mTvHelperAddress.setVisibility(View.GONE);
                }
            }
        });
    }

    public void showCallPhoneDialog(final String phoneNumber) {
        CallPhoneDialog phoneDialog = new CallPhoneDialog(mActivity);
        phoneDialog.setPhoneNum(phoneNumber);
        phoneDialog.show();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_confirm_order;
    }

    @Override
    public String getMessage() {
        return mEtMessage.getText().toString().trim();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.root_address:
                toChooseAddressActivity();
                break;
            case R.id.root_invoice:
                UmengUtils.onEvent(mActivity, R.string.umeng_order_confirme_choose_invoice);
                toInvoiceActivity();
                break;
            case R.id.root_coupon:
                UmengUtils.onEvent(mActivity, R.string.umeng_order_confirme_choose_coupon);
                toChooseDiscountCouponActivity();
                break;
            case R.id.root_red_packet:
                UmengUtils.onEvent(mActivity, R.string.umeng_order_confirme_choose_redPaper);
                toChooseRedPacketActivity();
                break;
            case R.id.layout_4:
                toInventoryActivity();
                break;
            case R.id.root_delivery:
                mPresenter.toChooseDeliveryActivity();
                break;
            case R.id.root_pay:
                toChoosePayWayActivity();
                break;
            case R.id.tv_submit_order:
                UmengUtils.onEvent(mActivity, R.string.umeng_order_confirme_sure);
                mPresenter.submitOrder();
                break;
        }
    }

    // payFee 支付手续费费率
    @Override
    public void setPayWayUI(String payWays, float payFee) {
        mTvPayWay.setText(payWays);
        if (payFee == 0) {
            mTvPayRate.setVisibility(View.GONE);
        } else {
            mTvPayRate.setVisibility(View.VISIBLE);
            mTvPayRate.setText(UIUtils.getString(R.string.pay_way_rate, payFee));
        }
    }

    @Override
    public void toChooseDeliveryActivity(String addressId) {
        ChooseShippingWayActivity.actionStart(mActivity, addressId);
    }

    @Override
    public void toChooseRedPacketActivity() {
        ChooseRedPacketActivity.actionStart(mActivity);
    }

    @Override
    public void toChooseDiscountCouponActivity() {
        ChooseCouponActivity.actionStart(mActivity);
    }

    @Override
    public void toChooseAddressActivity() {
        ChooseAddressActivity.actionStart(mActivity);
    }

    @Override
    public void onStop() {
        super.onStop();
        KeyboardUtils.closeKeyboard(mActivity);
    }

    @Override
    public void toInventoryActivity() {
        // 商品清单
        InventoryActivity.actionStart(mActivity);
    }

    @Override
    public void toInvoiceActivity() {
        ChooseInvoiceActivity.actionStart(mActivity);
    }

    @Override
    public void finishActivity() {
        mActivity.finish();
    }

    @Override
    public void showLoadingDialog() {
        if (mLoadingDialog == null) {
            mLoadingDialog = new LoadingDialog(mActivity);
            mLoadingDialog.setCanceledOnTouchOutside(false);
        }
        mLoadingDialog.show();
    }

    @Override
    public void hideLoadingDialog() {
        mLoadingDialog.dismiss();
    }


    @Override
    public void refreshConsignee(Consignee consignee) {
        mTvConsignee.setText(UIUtils.getString(R.string.confirm_order_consignee, consignee.getConsignee()));
        mTvPhone.setText(consignee.getTel());
        mTvTopAddress.setText(consignee.getAddress());
        mTvHelperAddress.setText(consignee.getAddress());
    }

    @Override
    public void refreshGoodsImages(List<String> goodsList, int totalGoodsCount) {
        try {
            mTvTotalCount.setText(UIUtils.getString(R.string.confirm_order_total_count, totalGoodsCount));

            String thumb1 = goodsList.get(0);
            ImageLoader.loadImageWithPlaceHolder(mActivity, mIvImage1, thumb1);

            String thumb2 = goodsList.get(1);
            mRatioLayout2.setVisibility(View.VISIBLE);
            ImageLoader.loadImageWithPlaceHolder(mActivity, mIvImage2, thumb2);

            String thumb3 = goodsList.get(2);
            mRatioLayout3.setVisibility(View.VISIBLE);
            ImageLoader.loadImageWithPlaceHolder(mActivity, mIvImage3, thumb3);

        } catch (IndexOutOfBoundsException e) {
            // 不足3张图片
        }
    }

    private void refreshInvoiceMoney(float invoiceFee) {
        mTvInvoiceMoney.setText(TextRenderUtils.getBeautyPrice(invoiceFee + "", null, UIUtils.dp2px(15), UIUtils.dp2px(11)));
    }

    @Override
    public void toOrderResultActivity(String orderPayId) {
        OrderResultActivity.actionStart(mActivity, orderPayId, null);
    }

    @Override
    public void refreshRedPacketUI(float redPacketReduce, int redPacketCount) {
        if (redPacketCount == 0) {
            mTvRedPacketUsefulCount.setVisibility(View.GONE);
            mTvRedPacketReduce.setText(getString(R.string.dont_have_red_packet));
            mTvRedPacketReduce.setTextColor(UIUtils.getColor(R.color.invoice_info));
        } else if (redPacketReduce == 0) {
            mTvRedPacketReduce.setText(getString(R.string.dont_choose_red_packet));
        } else {
            mTvRedPacketUsefulCount.setVisibility(View.VISIBLE);
            mTvRedPacketUsefulCount.setText(UIUtils.getString(R.string.red_packet_useful_count, redPacketCount));

            // 红包抵扣
            refreshRedPacketReduce(redPacketReduce);
        }
    }

    @Override
    public void refreshRedPacketReduce(float money) {
        SpannableStringBuilder builder = new SpannableStringBuilder();

        SpannableString redPacketPre = TextRenderUtils.getAppearanceText(getString(R.string.red_packet_reduce), R.style.RedPacketReduce);
        SpannableString redPacketMoney = TextRenderUtils.getAppearanceText("￥" + NumberFormatUtils.get2DecimalStringValue(money), R.style.RedPacketReduceMoney);

        builder.append(redPacketPre);
        builder.append(redPacketMoney);

        mTvRedPacketReduce.setText(builder);
    }

    private void refreshShippingMoney(float shippingFee) {
        SpannableStringBuilder builder = new SpannableStringBuilder();
        SpannableString deliveryPre = TextRenderUtils.getAppearanceText("+", R.style.ConfirmOrderDelivery);
        SpannableString deliveryPrice = TextRenderUtils.getBeautyPrice(shippingFee + "", null, UIUtils.dp2px(13), UIUtils.dp2px(10));
        builder.append(deliveryPre);
        builder.append(deliveryPrice);
        mTvDeliveryMoney.setText(builder);
    }

    @Override
    public void refreshInvoiceUI(String invRate, String invTitle) {
        mTvInvoiceRate.setText(UIUtils.getString(R.string.invoice_percent, invRate));
        mTvInvoiceInfo.setText(invTitle);
    }

    @Override
    public void showServicePhone(final String servicePhone) {
        mTvServiceNumber.setText(servicePhone);
        mRootServiceNumber.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showCallPhoneDialog(servicePhone);
            }
        });
    }

    @Override
    public void refreshCoupon(int couponCount, float couponMoney) {
        if (couponCount == 0) {
            mTvCouponUsefulCount.setVisibility(View.GONE);
            mTvCouponReduce.setText(getString(R.string.dont_have_coupon));
            mTvCouponReduce.setTextColor(UIUtils.getColor(R.color.invoice_info));
        } else if (couponCount == 0) {
            mTvCouponReduce.setText(getString(R.string.dont_choose_coupon));
        } else {
            mTvCouponUsefulCount.setVisibility(View.VISIBLE);
            mTvCouponUsefulCount.setText(UIUtils.getString(R.string.red_packet_useful_count, couponCount));

            // 优惠券抵扣
            refreshCouponReduce(couponMoney);
        }
    }

    private void refreshCouponReduce(float couponMoney) {
        SpannableStringBuilder builder = new SpannableStringBuilder();

        SpannableString redPacketPre = TextRenderUtils.getAppearanceText(getString(R.string.coupon_reduce), R.style.RedPacketReduce);
        SpannableString redPacketMoney = TextRenderUtils.getAppearanceText("￥" + NumberFormatUtils.get2DecimalStringValue(couponMoney), R.style.RedPacketReduceMoney);

        builder.append(redPacketPre);
        builder.append(redPacketMoney);

        mTvCouponReduce.setText(builder);
    }

    @Override
    public void toCashierActivity(String url, String orderPayId, String totalOnlinePay, boolean allOnlinePay) {
        CashierActivity.actionStart(mActivity, url, orderPayId, totalOnlinePay, allOnlinePay);
    }

    private void refreshPayWayMoney(float payWayFee) {
        mTvPayWayMoney.setText(TextRenderUtils.getBeautyPrice(payWayFee + "", null, UIUtils.dp2px(15), UIUtils.dp2px(11)));
    }

    private void refreshFinalMoney(float finalMoney) {
        SpannableStringBuilder builder = new SpannableStringBuilder();

        // 实付款:
        SpannableString totalPre = TextRenderUtils.getAppearanceText(getString(R.string.actual_money_hint), R.style.ConfirmOrderTotalPre);
        SpannableString priceStr = TextRenderUtils.getBeautyPrice(finalMoney + "", null, UIUtils.dp2px(17), UIUtils.dp2px(12));

        builder.append(totalPre);
        builder.append(priceStr);

        mTvSubmitMoney.setText(builder);
    }

    @Override
    public void refreshTotalFeeUI(float goodsTotalPrice, float shippingFee, float invMoney, float payWayFee, float submitPrice) {
        // 商品金额
        mTvStatisticsMoney.setText(TextRenderUtils.getBeautyPrice(goodsTotalPrice + "", null, UIUtils.dp2px(15), UIUtils.dp2px(11)));
        // 运费
        refreshShippingMoney(shippingFee);
        // 发票
        refreshInvoiceMoney(invMoney);
        // 手续费
        refreshPayWayMoney(payWayFee);
        // 实付款
        refreshFinalMoney(submitPrice);
    }

    @Override
    public void toMultiPayWaysActivity(String orderPayId) {
        MultiPayWaysActivity.actionStart(mActivity, orderPayId);
    }

    @Override
    public void toChoosePayWayActivity() {
        ChoosePayWayActivity.actionStart(mActivity);
    }

    @Override
    public void refreshContent(int result) {
        superRefreshLayoutState(result);
    }

    @Override
    public int checkResultObject(Object resultObject) {
        return superCheckListState(resultObject);
    }

    public void onBackPressed() {
        mPresenter.setNeedRefreshShoppingCart(false);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mKeyboardStateHelper.unregisterAllListeners();
    }

    @Override
    protected boolean isMultiLoadData() {
        return true;
    }
}
